import { Injectable, HttpException } from '@nestjs/common'
import { IUserService } from '../../interface/user/user-service.interface'
import { User } from '../../interface/user/user.interface'

@Injectable()
export class UserService implements IUserService {
  private static users: User[] = [
    {
      id: 1,
      name: '王雷',
      age: '20'
    },
    {
      id: 2,
      name: '刘宇峰',
      age: '30'
    },
    {
      id: 3,
      name: '张琪',
      age: '40'
    }
  ]

  /**
   * name
   */
  async findAll(): Promise<User[]> {
    // return Promise.resolve(this.users)
    return Promise.resolve(UserService.users)
  }

  /**
   * 查找某个用户
   * @param id 
   */
  async findOne(id: number): Promise<User> {
    const user = UserService.users.find(user => user.id == id)
    if(!user) {
      throw new HttpException('没有找到对应的用户', 404)
    }
    return Promise.resolve(user)
  }

  /**
   * 创建用户
   * @param user 
   */
  async create(user: User): Promise<User> {
    UserService.users.push(user)
    return Promise.resolve(user)
  }

  /**
   * 
   * @param user 修改某个用户
   */
  async edit(user: User): Promise<User> {
    const index = UserService.users.findIndex(item => item.id == user.id)
    if(index >= 0){
      UserService.users[index] = user
    }
    return Promise.resolve(user)
  }

  async remove(id: number): Promise<Boolean> {
    const index = UserService.users.findIndex(item => item.id == id)
    if(index >= 0){
      UserService.users.splice(index, 1)
    }
    return index >= 0
  }
}